<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Pc_Api_Standard_Login extends Controller_Pc_Api_Base
{

    public function before()
    {
        parent::before();
    }

    //根据手机验证码登录
    public function action_login_by_code()
    {
        $mobile = St_Filter::remove_xss($this->request_body->content->mobile);
        $code = St_Filter::remove_xss($this->request_body->content->checkcode);
        $openid = St_Filter::remove_xss($this->request_body->content->openid);
        $secret_code = St_Filter::remove_xss($this->request_body->content->secret_code);
        $fxcode = St_Filter::remove_xss($this->request_body->content->fxcode);
        //返回的会员id
        $mid = 0;
        $msg = array();
        if($mobile && $code)
        {
            $msg[] = 'has mobile and code';
            if($this->verify_code($code,$mobile,$secret_code))
            {
                $msg[] = 'checkcode ok';
                //检测是否存在
                $row = DB::select('mid')->from('member')->where('mobile','=',$mobile)->execute()->as_array();
                if($row[0]['mid']>0)
                {
                    $mid = $row[0]['mid'];
                }
                //如果不存在,则自动注册
                else
                {
                    $mid = St_Product::auto_reg($mobile);
                    Model_Member::add_reg_from($mid,4);
                }
                //检测是否绑定微信第三方
                if($openid)
                {
                    $ar = DB::select()->from('member_third')->where('mid','=',$mid)->execute()->as_array();
                    if(empty($ar[0]['mid']))
                    {
                        $data = array(
                            'mid' => $mid,
                            'openid' => $openid,
                            'come_from' => 'weixin'
                        );
                        DB::insert('member_third',array_keys($data))->values(array_values($data))->execute();
                    }
                }
            }

            if($mid)
            {

                // 检查是否是分销商
                $is_fenxiao = DB::select('fxcode')->from('fenxiao')->where('memberid','=',$mid)->execute()->current();
                if(!$is_fenxiao && !empty($fxcode))
                { // 不是分销商且分销商fxcode不为空
                    Model_Fenxiao::invite($mid, $fxcode);
                }

                $result = array(
                    'status' => true,
                    'mid' => $mid
                );
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            }
            else
            {
                $msg[] = 'checkcode false';


                $this->send_datagrams($this->client_info['id'], $msg, $this->client_info['secret_key']);
            }

        }
    }

    //根据微信openid 获取会员mid
    public function action_get_member_by_weixin()
    {
        $openid = Common::remove_xss($this->request_body->content->openid);
        $unionid = Common::remove_xss($this->request_body->content->unionid);
        $wxuid = Common::remove_xss($this->request_body->content->wxuid);
        $litpic = St_Filter::remove_xss($this->request_body->content->litpic);
        $nickname = St_Filter::remove_xss($this->request_body->content->nickname);
        $wxuid = $wxuid ? $wxuid : -1;
        $openid = empty($unionid) ? $openid : $unionid;
        $mid = 0;
        if(!empty($openid))
        {
            // $ar = DB::select()->from('member_third')->where('openid','=',$openid)->execute()->as_array();
            $sql = "SELECT t.mid,m.mobile FROM sline_member_third t INNER JOIN sline_member m  on(t.mid = m.mid) WHERE t.openid='{$openid}' and m.mobile <> '' LIMIT 1" ;
            $ar = DB::query(Database::SELECT, $sql)->execute()->as_array();

            if(!empty($ar[0]['mid']))
            {
                $mid = $ar[0]['mid'];
                $mobile = $ar[0]['mobile'];

                // 更新用户信息
                $upData = array();
                if($litpic)
                {
                    $upData['litpic'] = $litpic;
                }
                if($nickname)
                {
                    $upData['nickname'] = $nickname;
                }
                if(!empty($upData))
                {
                    DB::update('member')->set($upData)->where("mid","=",$mid)->execute();
                }
            }
        }
        $result = array(
            'status' => true,
            'mid' => $mid,
            'mobile' => $mobile
        );
        if(St_Functions::is_normal_app_install('mobiledistribution'))
        {
            $userFxCode = DB::select('fxcode')->from('fenxiao')->where('memberid','=',$mid)->and_where('status','=',1)->execute()->current();
            $result['fxcode'] = $userFxCode['fxcode'] ;
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);



    }
    //获取当前用户的手机号码
    public function action_getPhone()
    {
        //require_once dirname(dirname(__FILE__)) . "/xcx/wxBizDataCrypt.php";
        include_once  BASEPATH . "/plugins/api/vendor/xcx/wxBizDataCrypt.php";

        $appid = Common::remove_xss($this->request_body->content->appid);
        $sessionKey = Common::remove_xss($this->request_body->content->sessionKey);
        $encryptedData = Common::remove_xss($this->request_body->content->encryptedData);
        $iv = Common::remove_xss($this->request_body->content->iv);
        // 去掉获取到iv的值中间有空格
        $new_iv = str_replace(' ', '', $iv);

        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $new_iv, $data );
        // 记录手机获取状态
        $log = array(
            'time'      =>  date('Y-m-d H:i:s',time()),
            'data'      =>  $data,
            'errCode'   =>  $errCode,
            'iv'        =>  $iv,
            'new_iv'    =>  $new_iv,
            'encryptedData' => $encryptedData,
            'sessionKey'=>  $sessionKey,
            'appid'     =>  $appid
        );

        $this->send_datagrams($this->client_info['id'], array('data' => $data , 'errCode'=>$errCode), $this->client_info['secret_key']);
    }
    //手机号码登录
    public function action_login_by_phone()
    {
        $mobile = St_Filter::remove_xss($this->request_body->content->mobile);
        $openid = St_Filter::remove_xss($this->request_body->content->openid);
        $fxcode = St_Filter::remove_xss($this->request_body->content->fxcode);
        $reg_arr['nickname'] = St_Filter::remove_xss($this->request_body->content->nickname);
        $reg_arr['litpic'] = St_Filter::remove_xss($this->request_body->content->litpic);
        $unionid = St_Filter::remove_xss($this->request_body->content->unionid);
        $openid = empty($unionid) ? $openid : $unionid;

        //返回的会员id
        $mid = 0;
        $msg = array();
        if($mobile)
        {
            // 小程序注册需要判断用户是不是微信快速登录注册了账号但没有绑定手机号码
            // 检测用户是否存在
            $row = DB::select('mid')->from('member')->where('mobile','=',$mobile)->execute()->current();

            if($row['mid']>0)
            {
                $mid = $row['mid'];
                //
                $ar = DB::select()->from('member_third')->where('mid','=',$mid)->and_where('come_from','=','weixin')->execute()->current();
                if($ar['openid']!=$openid){
                    DB::update('member_third')->set(array('openid' => $openid))->where('id','=',$ar['id'])->execute();
                }
            }
            else
            {
                // 检测是否绑定微信第三方
                $third = DB::select()->from('member_third')->where('openid','=',$openid)->and_where('come_from','=','weixin')->execute()->current();
                // 当绑定了第三方
                if(!empty($third['mid']))
                {
                    DB::update('member')->set(array('mobile' => $mobile))->where('mid','=',$third['mid'])->execute();
                    $mid = $third['mid'];
                }
                else
                {
                    //如果不存在,则自动注册
                    $mid = St_Product::auto_reg($mobile,$reg_arr);
                    //加入分销
                    Model_Member::add_reg_from($mid,4);
                    $data = array(
                        'mid' => $mid,
                        'openid' => $openid,
                        'come_from' => 'weixin'
                    );
                    DB::insert('member_third',array_keys($data))->values(array_values($data))->execute();
                }
            }

            if($mid)
            {
                $result = array(
                    'status' => true,
                    'mid' => $mid
                );
                if(St_Functions::is_normal_app_install('mobiledistribution'))
                {

                    // 检查是否是分销商
                    $is_fenxiao = DB::select('fxcode','status')->from('fenxiao')->where('memberid','=',$mid)->execute()->current();
                    if(!$is_fenxiao && !empty($fxcode))
                    { // 不是分销商且分销商fxcode不为空
                        Model_Fenxiao::invite($mid, $fxcode);
                    }

                    if($is_fenxiao && $is_fenxiao['status'] == 1)
                    { // 是分销且分销状态为1
                        $result['fxcode'] = $is_fenxiao['fxcode'];
                    }
                }
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            }
            else
            {
                $msg[] = 'checkcode false';
                $this->send_datagrams($this->client_info['id'], $msg, $this->client_info['secret_key']);
            }

        }
    }

    /**
     * @function 检测验证码是否正确
     * @param $code
     * @param $mobile
     * @return int
     */
    private function verify_code($code,$mobile,$secret_code)
    {
        $code = md5($code.$mobile);
        return $code == $secret_code ? 1 : 0;
    }

    //根据mid判断是否为有效客户
    public function action_is_effective_member()
    {

        $mid=Common::remove_xss($this->request_body->content->mid);

        if (!empty($mid)) {
            $sql="SELECT mid FROM sline_member WHERE mid='{$mid}' LIMIT 1";
            $ar = DB::query(Database::SELECT, $sql)->execute()->as_array();
            if ($ar) {
                $rdata = array('error'=>0,'errormsg'=>'有效账号','errordata'=>$ar);
                $this->send_datagrams($this->client_info['id'], $rdata, $this->client_info['secret_key']);
            } else {
                $rdata=array('error'=>1,'errormsg'=>'无效账号','errordata'=>array());
                $this->send_datagrams($this->client_info['id'], $rdata, $this->client_info['secret_key']);
            }
        } else {

            $rdata=array('error'=>1,'errormsg'=>'无效账号','errordata'=>array());
            $this->send_datagrams($this->client_info['id'], $rdata, $this->client_info['secret_key']);

        }
    }



}